/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.common.filter;

import com.huawei.housekeeper.common.properties.HeaderMapRequestWrapper;

import lombok.extern.log4j.Log4j2;

import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * url解析
 *
 * @author y84241604
 * @since 2022-06-22
 */
@Log4j2
@Component
public class DomainFilter implements Filter, Ordered {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            log.info(request.toString());
            String domain = request.getHeader("Referer");
            log.info("source domain " + domain);
            domain = domain.substring(7).split("\\.")[0];
            log.info("result domain " + domain);
            HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(request);
            requestWrapper.addHeader("tenantDomain", domain);
            filterChain.doFilter(requestWrapper, servletResponse);

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
